package cn.harry.cabinet.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import cn.harry.cabinet.hardware.HardwareDeviceManager
import cn.harry.cabinet.hardware.SerialCommunicationListener
import cn.harry.cabinet.hardware.SerialCommunicationListenerAdapter
import cn.harry.cabinet.hardware.SerialPortManager
import cn.harry.cabinet.hardware.device.CardReaderDevice
import kotlinx.coroutines.launch

/**
 * 硬件管理ViewModel
 * 负责串口通信和硬件设备的统一管理
 * 使用新的HardwareDeviceManager和SerialCommunicationListener接口
 */
class HardwareViewModel(application: Application) : AndroidViewModel(application) {
    
    companion object {
        private const val TAG = "HardwareViewModel"
    }
    
    private val serialPortManager = SerialPortManager.getInstance()
    private val hardwareDeviceManager = HardwareDeviceManager.getInstance(application)
    
    // 串口连接状态
    private val _serialConnectionState = MutableLiveData<SerialPortManager.ConnectionState>()
    // 操作状态
    private val _operationStatus = MutableLiveData<String>()

    // 错误信息
    private val _errorMessage = MutableLiveData<String>()
    val errorMessage: LiveData<String> = _errorMessage
    
    // 通信日志
    private val _communicationLog = MutableLiveData<List<String>>()

    // 日志列表
    private val logList = mutableListOf<String>()
    
    // 刷卡事件
    private val _cardReadEvent = MutableLiveData<CardReaderDevice.CardInfo>()
    val cardReadEvent: LiveData<CardReaderDevice.CardInfo> = _cardReadEvent

    // 串口通信监听器
    private val communicationListener = object : SerialCommunicationListenerAdapter() {
        
        override fun onConnectionSuccess(devicePath: String, config: SerialPortManager.SerialConfig) {
            addLog("✅ 连接成功: $devicePath (波特率: ${config.baudRate})")
            _operationStatus.postValue("串口连接成功: $devicePath")
        }
        
        override fun onConnectionFailed(devicePath: String, error: String, exception: Exception?) {
            addLog("❌ 连接失败: $devicePath - $error")
            _errorMessage.postValue("串口连接失败: $error")
        }
        
        override fun onConnectionClosed(devicePath: String, reason: String) {
            addLog("🔌 连接关闭: $devicePath - $reason")
            _operationStatus.postValue("串口连接已关闭: $reason")
        }
        
        override fun onDataSent(devicePath: String, data: ByteArray, success: Boolean) {
            val status = if (success) "✅" else "❌"
            addLog("📤 $status 发送数据: $devicePath (${data.size} 字节)")
        }
        
        override fun onDataReceived(devicePath: String, data: ByteArray, timestamp: Long) {
            addLog("📥 接收数据: $devicePath (${data.size} 字节)")
        }
        
        override fun onCommunicationTimeout(devicePath: String, operation: String, timeoutMs: Long) {
            addLog("⏰ 通信超时: $devicePath - $operation (${timeoutMs}ms)")
            _errorMessage.postValue("通信超时: $operation")
        }
        
        override fun onCommunicationError(devicePath: String, errorType: SerialCommunicationListener.ErrorType, errorMessage: String, exception: Exception?) {
            addLog("🚨 通信错误: $devicePath - $errorType: $errorMessage")
            _errorMessage.postValue("通信错误: $errorMessage")
        }
        
        override fun onConnectionStateChanged(devicePath: String, oldState: SerialPortManager.ConnectionState, newState: SerialPortManager.ConnectionState) {
            addLog("🔄 状态变化: $devicePath - $oldState → $newState")
        }
        
        override fun onDeviceStatusChanged(deviceAddress: Byte, deviceName: String, oldStatus: String, newStatus: String) {
            addLog("📟 设备状态: $deviceName (0x${deviceAddress.toString(16)}) - $oldStatus → $newStatus")
        }
    }
    
    init {
        // 注册通信监听器
        serialPortManager.addCommunicationListener(communicationListener)
        
        // 监听串口连接状态
        viewModelScope.launch {
            serialPortManager.connectionState.collect { state ->
                _serialConnectionState.value = state
            }
        }

        // 监听连接状态
        viewModelScope.launch {
            hardwareDeviceManager.isConnected.collect { connected ->
                if (connected) {
                    _operationStatus.value = "硬件设备已连接"
                    
                    // 监听刷卡器读卡事件
                    val cardReader = hardwareDeviceManager.getCardReaderDevice()
                    cardReader?.cardReadEvent?.collect { cardInfo ->
                        cardInfo?.let {
                            _cardReadEvent.postValue(it)
                            addLog("💳 刷卡成功: ${it.cardId} (${it.cardType})")
                        }
                    }
                } else {
                    _operationStatus.value = "硬件设备未连接"
                }
            }
        }
        
        addLog("🚀 硬件管理系统已启动")
    }
    
    /**
     * 添加日志
     */
    private fun addLog(message: String) {
        val timestamp = java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.getDefault())
            .format(java.util.Date())
        val logEntry = "[$timestamp] $message"
        
        logList.add(0, logEntry) // 添加到顶部
        
        // 限制日志数量
        if (logList.size > 100) {
            logList.removeAt(logList.size - 1)
        }
        
        _communicationLog.postValue(logList.toList())
        Log.d(TAG, logEntry)
    }


    /**
     * 清除错误信息
     */
    fun clearErrorMessage() {
        _errorMessage.value = ""
    }

    override fun onCleared() {
        super.onCleared()
        
        // 移除通信监听器
        serialPortManager.removeCommunicationListener(communicationListener)
        
        // 断开硬件设备连接
        hardwareDeviceManager.disconnectAll()
        
        // 释放资源
        hardwareDeviceManager.release()
        
        addLog("🛑 硬件管理系统已停止")
        Log.d(TAG, "HardwareViewModel 资源已释放")
    }
}